package com.example.smartcanteen.Config;

import ch.qos.logback.core.util.StringUtil;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.smartcanteen.utils.JwtUtil;
import com.example.smartcanteen.utils.ResponseMessage;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request
            , HttpServletResponse response, Object handler) throws Exception {
       String token=request.getHeader("token");
        if (StringUtil.isNullOrEmpty(token)) {
            handleUnauthorized(response, "尚未登录，请重新登录");
            return false;
        }
        try {
            JwtUtil.verifyToken(token);
        } catch (JWTVerificationException e) {
            handleUnauthorized(response, "token 异常");
            return false;
        }
        return true;
    }
    private void handleUnauthorized(HttpServletResponse response, String message) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setSuccess(false);
        responseMessage.setMessage(message);

        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        String jsonResponse = objectMapper.writeValueAsString(responseMessage);
        response.getWriter().write(jsonResponse);
    }
}
